package com.mz.mattress.admin.api;

import com.mz.mattress.admin.interceptor.ApiLogAspect;
import com.mz.mattress.admin.service.SysFileService;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.enums.FilePathEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private ApiLogAspect apiLogAspect;

    @GetMapping("/test")
    public Result test() {
        return Result.ok();
    }

    @GetMapping("/help")
    public void help(HttpServletResponse response) {

        StringBuilder sb = new StringBuilder();
        sb.append("\r\n changeLog 打开或关闭显示全日志");
        String str = sb.toString();

        outputHtml(response, str);
    }

    private void outputHtml(HttpServletResponse response, String str) {
        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try {
            response.getWriter().write(str);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    //上传文件 图片
    @PostMapping(value = "/upload")
    public Result<String> upload(@RequestParam("filePath") Integer filePath, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        return sysFileService.upload(file, FilePathEnum.valueOf(filePath));
    }

    @GetMapping("/changeLog")
    public String changeLog() {
        apiLogAspect.changeLog();
        return "ok";
    }
}
